#pragma once
#include <string>
#include <cstring>
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cerrno>
#include <cstdlib>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <functional>

namespace Server
{
    enum
    {
        USAGE_ERR = 1,
        SOCKET_ERR,
        BIND_ERR,
        OPEN_ERR
    };

    static const std::string defaultIp = "0.0.0.0";
    static const int gnum = 1024;

    typedef std::function<void(int,std::string, uint16_t, std::string)> func_t;

    class udpServer
    {
    public:
        udpServer(const func_t &cb, const uint16_t port, const std::string ip = defaultIp)
            : _callback(cb), _port(port), _ip(ip), _sockfd(-1)
        {
        }

        void initServer()
        {
            // 1.创建套接字
            _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sockfd == -1)
            {
                std::cerr << "socket error: " << errno << " : " << strerror(errno) << std::endl;
                exit(SOCKET_ERR);
            }
            // 告诉操作系统，当前的IP和PORT是多少，上面的代码只是把数据存在堆栈上
            // 2.绑定IP接口
            struct sockaddr_in local;
            bzero(&local, sizeof local); // 清空结构体
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);
            // local.sin_addr.s_addr = INADDR_ANY;

            int n = bind(_sockfd, (struct sockaddr *)&local, sizeof local);
            if (n == -1)
            {
                std::cerr << "bind error: " << errno << " : " << strerror(errno) << std::endl;
                exit(BIND_ERR);
            }
        }

        void start()
        {
            // 服务器的本质其实就是死循环
            char buffer[gnum];
            for (;;)
            {
                struct sockaddr_in peer;
                socklen_t len = sizeof peer;
                ssize_t s = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, (socklen_t *)&len);
                // 1.数据是什么2.谁发的
                if (s > 0)
                {
                    std::string clientip = inet_ntoa(peer.sin_addr);
                    uint16_t clientport = ntohs(peer.sin_port);
                    std::string massage = buffer;

                    std::cout << clientip << "[" << clientport << "]# " << massage << std::endl;
                    _callback(_sockfd, clientip, clientport, massage);
                }
            }
        }

        ~udpServer()
        {
        }

    private:
        uint16_t _port;
        std::string _ip; // 实际上，一款网络服务器不建议只绑定一个IP
        int _sockfd;
        func_t _callback;
    };
}
